using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class Plant : MonoBehaviour, IPointerDownHandler
{
    private Texture2D mainTex;
    public int width = 256; // 可以移除这个变量，如果你的纹理大小是固定的
    public int height = 256; // 可以移除这个变量，如果你的纹理大小是固定的
    public int plantSize = 8;

    private void Start()
    {
        mainTex = GetComponent<RawImage>().mainTexture as Texture2D;
        // if (mainTex == null)
        // {
        //     Debug.LogError("No Texture2D found on RawImage component.");
        // }
    }

    public void PlantByPixel(int x, int y)
    {
        // for (int i = x - plantSize; i < x + plantSize; i++)
        // {
        //     for (int j = y - plantSize; j < y + plantSize; j++)
        //     {
        //         if (i >= 0 && i < mainTex.width && j >= 0 && j < mainTex.height) // 边界检查
        //         {
        //             mainTex.SetPixel(i, j, Color.white);
        //         }
        //     }
        // }
        mainTex.SetPixel(x, y, Color.white);
        mainTex.Apply();
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        Vector2 localCursor;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(GetComponent<RawImage>().rectTransform, eventData.position, eventData.pressEventCamera, out localCursor);

        // 将localCursor转换为纹理坐标
        float x = (localCursor.x / GetComponent<RawImage>().rectTransform.rect.width + 0.5f) * mainTex.width;
        float y = (localCursor.y / GetComponent<RawImage>().rectTransform.rect.height + 0.5f) * mainTex.height;

        PlantByPixel((int)x, (int)y);
    }
}